package is.ru.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created in IntelliJ IDEA.
 * Students: Jón Geir Sigurbjörnsson, Kristinn Helgi Hilmarsson, Jón Rúnar Arnarsson
 * Class: T-408-STNE, Stýrikerfi og netkerfi, 2011-1
 * Project: Programming assignment 3: HTTP web server
 * Date: 16.3.2011
 * Time: 20:17
 */

public class TCPConnectionHandler
{
    private ServerSocket serverSocket = null;

    public TCPConnectionHandler(int port)
    {
        //Try to make the connection with the given port
        try
        {
            serverSocket = new ServerSocket(port);
        } catch (IOException e)
        {
            System.out.println("TCPConnectionHandler IOException");
            e.printStackTrace();
        }
    }

    public void start()
    {
        System.out.println("Starting TCP server on port: " + serverSocket.getLocalPort() + ", address: " + serverSocket.getLocalSocketAddress());

        while (true)
        {
            // Wait for the socket to be accepted, before  we send it to the RequestHandler
            try
            {
                Socket socket = serverSocket.accept();
                new TCPRequestHandler(socket);
            } catch (IOException e)
            {
                System.out.println("TCPConnectionHandler IOException");
                e.printStackTrace();
                break;
            }
        }
    }
}
